package com.miui.theme.custom.viewmodel

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.miui.theme.custom.data.ConfigDataStore
import com.miui.theme.custom.utils.MySQLHelper
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.launch

class MainViewModel(configDataStore: ConfigDataStore) : ViewModel() {
    private val _tables = MutableStateFlow<List<String>>(emptyList())
    val tables = _tables.asStateFlow()

    private lateinit var helper: MySQLHelper

    init {
        viewModelScope.launch {
            val config = configDataStore.config.first()!!
            helper = MySQLHelper(config)
            fetchTables()
        }
    }

    fun fetchTables() {
        viewModelScope.launch {
            val result = helper.executeQuery("SHOW TABLES")
            if (result.isSuccess) {
                val rs = result.getOrThrow()
                val tableList = mutableListOf<String>()
                while (rs.next()) {
                    tableList.add(rs.getString(1))
                }
                _tables.value = tableList
            }
        }
    }

    fun createTable(tableName: String, columns: String) {
        viewModelScope.launch {
            val sql = "CREATE TABLE $tableName ($columns)"
            val result = helper.executeUpdate(sql)
            if (result.isSuccess) {
                fetchTables()
            }
        }
    }

    fun disconnect() {
        viewModelScope.launch {
            if (::helper.isInitialized) {
                helper.disconnect()
            }
        }
    }
}